package cn.bdqn.service.impl;

import cn.bdqn.domain.BaseRegister;
import cn.bdqn.mapper.BaseRegisterMapper;
import cn.bdqn.service.BaseRegisterService;
import cn.bdqn.utils.MD5Util;
import cn.bdqn.utils.httputil.HttpUtils;
import cn.bdqn.utils.result.Page;
import cn.bdqn.utils.httputil.SendMailUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 基地注册业务接口实现类
 * @author dkj
 */
@Service("baseRegisterService")
public class BaseRegisterServiceImpl implements BaseRegisterService {

    /**
     * 基地注册接口
     */
    @Autowired
    private BaseRegisterMapper baseRegisterMapper;

    /**
     * 分页查询
     * @param pageNum 起始页数
     * @return
     */
    @Override
    public Page queryPage(Integer pageNum) {
        //每页显示的数量
        Integer pageSize = 10;
        //开启分页 pageNum > 0 ? pageNum:1 判断当前页数是否大于0
        PageHelper.startPage(pageNum > 0 ? pageNum:1,pageSize);
        //查询全部数据
        List<BaseRegister> baseRegisters = baseRegisterMapper.selectAll();
        //分页
        PageInfo<BaseRegister> baseRegisterPages = new PageInfo<BaseRegister>(baseRegisters);
        //封装分页数据
        Page page = new Page();
        //分页之后的数据
        page.setMenuList(baseRegisterPages.getList());
        //总记录数
        page.setTotalRecord((int)baseRegisterPages.getTotal());
        //返回封装的分页对象
        return page;
    }

    /**
     * 根据手机号和密码查询
     * @param phone
     * @param pwd
     * @return
     */
    @Override
    public BaseRegister queryByPhoneAndPwd(String phone, String pwd) {
        //根据手机号和密码查询基地账号
        return baseRegisterMapper.selectByPhoneAndPwd(phone, MD5Util.encode(pwd));
    }

    /**
     * 添加一个基地账号
     * @param baseRegister
     */
    @Override
    public void save(BaseRegister baseRegister) {

        //MD5加密密码
        baseRegister.setPwd(MD5Util.encode(baseRegister.getPwd()));
        //设置token
        baseRegister.setToken(UUID.randomUUID().toString());
        //调用添加方法
        baseRegisterMapper.insert(baseRegister);
    }

    /**
     * 根据手机号查询基地用户是否存在
     * @param phone
     * @return
     */
    @Override
    public Integer queryByPhone(String phone) {
        //调用查询方法
        return baseRegisterMapper.selectByPhone(phone);
    }

    /**
     * 根据邮箱查询基地用户是否存在
     * @param email
     * @return
     */
    @Override
    public Integer queryByEmail(String email) {
        //调用查询方法
        return baseRegisterMapper.selectByEmail(email);
    }

    /**
     * 短信验证
     * @param phone
     * @return
     */
    @Override
    public String verification(String phone)throws Exception {
//        String host = "https://feginesms.market.alicloudapi.com";
//        String path = "/codeNotice";
//        String method = "GET";
//        //阿里云appCode
//        String appcode = "a55b99e70e2b4860a0fe8056265719b8";
//        Map<String, String> headers = new HashMap<String, String>();
////        最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        Map<String, String> querys = new HashMap<String, String>();
////        生成验证码
        Long param = Math.round((Math.random()+1) * 1000);
////        //这里是验证码哈
//        querys.put("param", param.toString());
////        //然后这里是手机号
//        querys.put("phone", phone);
////        //签名编号【联系旺旺客服申请，测试请用1】
//        querys.put("sign", "1");
////        //模板编号【联系旺旺客服申请，测试请用1~21】
//        querys.put("skin", "1");
////        //JDK 1.8示例代码请在这里下载：  http://code.fegine.com/Tools.zip
//        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//        //System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
//        //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
//        //获取response的body
//        String message = EntityUtils.toString(response.getEntity());
//        System.out.println(message);
////        转换为json
//        JSONObject jsonObject = JSONObject.parseObject(message);
//        String ok =  (String) jsonObject.get("Message");
//        String flag = "OK";
        System.out.println(param.toString());
//        if (flag.equals(ok)){
            return param.toString();
//        }else {
            //抛一个异常
//            throw new Exception("失败");
//        }
    }

    /**
     * 邮箱短信验证
     * @param email
     * @return
     */
    @Override
    public String emailVerification(String email) throws Exception{

        SendMailUtil sendMailUtil = new SendMailUtil();

        String code="";
        /**随机产生验证码*/
        Random rd=new Random();
        while(code.length()<4){
            code+=rd.nextInt(10);
        }

        /**如果验证码发送成功*/
        if(sendMailUtil.sendHtmlMail(email, "yjjs", code)){
            return code;
        }else{
            /**抛一个异常*/
            throw new Exception("失败");
        }
    }

    /**
     * 根据id修改基地账号对象
     * 根据手机号修改密码
     * @param baseRegister
     */
    @Override
    public BaseRegister updateById(BaseRegister baseRegister) {
        //使用md5加密
        baseRegister.setPwd(MD5Util.encode(baseRegister.getPwd()));
        //设置token
        baseRegister.setToken(UUID.randomUUID().toString());
        //更新对象
        baseRegisterMapper.updateByPrimaryKeySelective(baseRegister);
        //返回最新对象数据
        return baseRegister;
    }

    /**
     * 根据基地账号id和原密码修改新的密码
     * @param id 基地账号id
     * @param oldPwd 旧密码
     * @param newPwd 新密码
     */
    @Override
    public BaseRegister updateByIdAndOldPwd(Integer id, String oldPwd, String newPwd) {

        //查询当前对象
        BaseRegister baseRegister = baseRegisterMapper.selectByPrimaryKey(id);

        System.out.println(baseRegister);
        //判断是否密码相等
        if (baseRegister.getPwd().equals(MD5Util.encode(oldPwd))){
            //修改新密码
            baseRegister.setPwd(MD5Util.encode(newPwd));
            //设置token
            baseRegister.setToken(UUID.randomUUID().toString());
            //修改
            baseRegisterMapper.updateByPrimaryKeySelective(baseRegister);
            //返回
            return baseRegister;
        }
        //如果不一样，返回null
        return null;
    }


    /**
     * 根据主键id查询
     * @param id
     * @return
     */
    @Override
    public BaseRegister queryByPrimaryKey(Integer id){
        //根据id查询用户
        return baseRegisterMapper.selectByPrimaryKey(id);
    }

    /**
     * 更新账号
     * @param baseRegister
     * @return
     */
    @Override
    public BaseRegister updateBaseUser(BaseRegister baseRegister) {

        //更新token
        baseRegister.setToken(UUID.randomUUID().toString());
        //更新对象
        baseRegisterMapper.updateByPrimaryKeySelective(baseRegister);

        return baseRegister;

    }


}
